package com.zhihao.takeaway.controller;

import com.zhihao.takeaway.common.utils.DateTool;
import com.zhihao.takeaway.common.utils.EasyUITable;
import com.zhihao.takeaway.common.utils.JwtUtil;
import com.zhihao.takeaway.common.utils.Result;
import com.zhihao.takeaway.entity.ShoppingCart;
import com.zhihao.takeaway.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private ShoppingCartService shoppingCartService;

    @GetMapping("/getShoppingCartNum")
    public Result getShoppingCartNum(){
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            Integer num = shoppingCartService.getShoppingCartData(UserId).getTotal();
            result.setData(num);
            result.success("显示购物车物品数量");
        }
        return  result;
    }
    @GetMapping("/getShoppingCartData")
    public Result getShoppingCartData(){
//        System.out.println("可以到达");
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            EasyUITable easyUITable =  shoppingCartService.getShoppingCartData(UserId);
            result.setData(easyUITable);
            result.success("成功查询");
        }
        return result;
    }
    @PostMapping("/cancel")
    public Result cancel(String id){
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            Integer num = shoppingCartService.cancel(id);
            if(num == 0){
                result.fail("删除失败，请重试");
            }else{
                result.success("删除成功");
            }
        }
        return result;
    }
    @PostMapping("/save")
    public Result addToShoppingCart(@RequestBody ShoppingCart shoppingCart){
        Result result = new Result();
        String UserId = getUserId();
        if(UserId == null || UserId.equals("")){
            result.fail("当前用户未登录");
        }else{
            shoppingCart.setUserId(UserId);
            shoppingCart.setCreateTime(DateTool.getCurrTime());
            Integer insert = shoppingCartService.insert(shoppingCart);
            if(insert > 0) {
                result.success("添加成功");
            }else{
                result.fail("添加失败，请重试");
            }
        }
        return result;
    }

    public String getUserId(){
        String token = request.getHeader("token");
        String UserId = JwtUtil.validateToken(token);
        return UserId;
    }
}
